package com.soar.tbox.protocol;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;

import com.soar.tbox.CommandStorage;
import com.soar.tbox.DisplayHandler;
import com.soar.tbox.Messenger;
import com.soar.tbox.bean.Command;
import com.soar.tbox.bean.Paramter;
import com.soar.tbox.util.Converts;
import com.soar.tbox.util.LogUtil;
import com.soar.tbox.util.SettingHelper;

/**
 * 车辆状态查询
 * 
 * @author songjunjie
 * 
 */
public class Protocol0501 implements Protocol {
	/**
	 * 指令名. 车辆位置查询
	 */
	private static final String NAME = "0501";

	private Command cmd = null;
	private String serialNum = null;

	public Protocol0501(Command cmd, String serialNum) {
		this.cmd = cmd;
		this.serialNum = serialNum;
	}

	@SuppressLint("SimpleDateFormat")
	@Override
	public void handle() {
		DisplayHandler.show("执行车辆位置查询指令");
		
		Command resultCommand = CommandStorage.getCommand(NAME);
		resultCommand.setSerialNum(serialNum);
		List<Paramter> paramlist = resultCommand.getParamterList();
		// 给请求指令设置位置信息
		for (Paramter param : paramlist) {
			byte[] key = param.getKey();
			if (key[0] == 0x07) {// 表示是位置信息
				String position_info = SettingHelper.getSetting().get(
						"position_info");
				if (position_info == null || position_info.length() == 0) {
					Exception e = new Exception(
							"车辆位置信息(position_info),没有在配置文件setting.xml配置.");
					DisplayHandler.show("车辆位置信息(position_info),没有在配置文件setting.xml配置.");
					LogUtil.error("", e);
					return;
				}
				position_info = position_info.trim();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				String time = sdf.format(new Date());
				// 用当前时间替换位置信息中的gps时间参数.
				position_info.replaceAll("#time", time);
				byte[] val = position_info.getBytes();
				param.setValue(val);// 设置位置信息
				byte len = Converts.intToUbyte(val.length);
				param.setLen(new byte[] { len });// 设置参数长度
				break;
			}
		}
		Messenger messenger = new Messenger();
		try {
			messenger.send(resultCommand, false);
		} catch (Exception e) {
			DisplayHandler.show("发送指令出现错误."+e.getMessage());
			LogUtil.error("", e);
			e.printStackTrace();
		}
		
	}
}